<?php
require_once 'facebookAPIHelper.php';
//return an array of Friend objects
function getFriends(){

    try{
        $response = callGraphAPI('/me/friends');
    }catch(FacebookApiException $e){
        throw($e);
    }
    $arr = Array();
    if(!empty($response['data'])){
        $friends = $response['data'];

        foreach ($friends as $friend) {
            $f = new Friend($friend['id'], $friend['name']);
            $arr[$friend['id']] = $f;
        }
    }
    return $arr;
}

//get all data using Multiquery
//param $mode : flags (1:Message, 2:Post, 4:Comment, 8:Like And flags can be added for example, 1+2 = 3 : Message+Post flags)
//return $data
function getAllDataFromFQL(){

    $args = func_get_args();
    if(isset($args['0'])){
        $mode = $args['0'];
    }else{
        $mode = 0;
    }

    $data = null;
    
    try{
    
        $queries = array();
        
        if(($mode & MESSAGE_FLAG) === MESSAGE_FLAG){
            //MESSAGE QUERIES
            
            $threadQuery = "select thread_id, recipients from thread where folder_id = 0 or folder_id = 1 and updated_time > ".QUERY_SINCE;
            
            $messageQuery = "select thread_id, author_id from message where thread_id in (
                            	select thread_id from #threadQuery
                        	) and created_time > ".QUERY_SINCE;
            
            $queries['threadQuery'] = $threadQuery;
            $queries['messageQuery'] = $messageQuery;
        }
        
        if(($mode & POST_FLAG) === POST_FLAG){
            //POST QUERY
            //Friends' posts on my wall
            $friendsPostQuery = "SELECT actor_id FROM stream 
                                WHERE source_id = me() AND actor_id IN (
                                	SELECT uid1 FROM friend WHERE uid2 = me()
                                ) AND created_time >".QUERY_SINCE;
            
            $queries['friendsPostQuery'] = $friendsPostQuery;
        }
        
        if(($mode & COMMENT_FLAG) === COMMENT_FLAG){
            //COMMENTS QUERIES
            //Friends' comments on my post
            $friendsCommentQuery = "SELECT fromid FROM comment
                			WHERE fromid != me() 
                			AND (
                				object_id IN (SELECT note_id FROM note WHERE uid = me())
                				OR object_id IN (SELECT status_id FROM status WHERE uid = me())
                				OR object_id IN (SELECT link_id FROM link WHERE owner = me())
                			) AND time >".QUERY_SINCE;

            $queries['friendsCommentQuery'] = $friendsCommentQuery;
        
            //My comments on friends' posts
            $myCommentNoteQuery = "SELECT uid FROM note WHERE note_id IN (
                SELECT object_id FROM comment 
                WHERE fromid = me() AND object_id IN (
                    SELECT note_id FROM note WHERE uid IN (
                        SELECT uid2 FROM friend WHERE uid1 = me()
                    )
                ) AND time >".QUERY_SINCE."
            )";
        
            $myCommentStatusQuery = "SELECT uid FROM status WHERE status_id IN (
                SELECT object_id FROM comment 
                WHERE fromid = me() AND object_id IN (
                    SELECT status_id FROM status WHERE uid IN (
                        SELECT uid2 FROM friend WHERE uid1 = me()
                    )
                ) AND time >".QUERY_SINCE."
            )";
        
            $myCommentLinkQuery = "SELECT owner FROM link WHERE link_id IN (
                SELECT object_id FROM comment 
                WHERE fromid = me() AND object_id IN (
                    SELECT link_id FROM link WHERE owner IN (
                        SELECT uid2 FROM friend WHERE uid1 = me()
                    )
                ) AND time >".QUERY_SINCE."
            )";
            
            $queries['myCommentNoteQuery'] = $myCommentNoteQuery;
            $queries['myCommentStatusQuery'] = $myCommentStatusQuery;
            $queries['myCommentLinkQuery'] = $myCommentLinkQuery;
     
        }
        
        if(($mode & LIKE_FLAG) === LIKE_FLAG){
            //LIKES QUERIES
            //Friends' likes
            $friendsLikesQuery = "SELECT user_id FROM like 
                			WHERE user_id != me() 
                			AND (
                				object_id IN (SELECT note_id FROM note WHERE uid = me() AND created_time > ".QUERY_SINCE.")
                				OR object_id IN (SELECT status_id FROM status WHERE uid = me() AND time > ".QUERY_SINCE.")
                				OR object_id IN (SELECT link_id FROM link WHERE owner = me() AND created_time > ".QUERY_SINCE.")
                			)";

            $queries['friendsLikesQuery'] = $friendsLikesQuery;
                            
            //My likes
            $myLikeNoteQuery = "SELECT uid FROM note WHERE note_id IN (
                                SELECT object_id FROM like 
                                WHERE user_id = me() AND object_id IN (
                                    SELECT note_id FROM note WHERE uid IN (
                                        SELECT uid2 FROM friend WHERE uid1 = me()
                                    ) AND created_time > ".QUERY_SINCE."
                                )
                            )";
        
            $myLikeStatusQuery = "SELECT uid FROM status WHERE status_id IN (
                                SELECT object_id FROM like 
                                WHERE user_id = me() AND object_id IN (
                                    SELECT status_id FROM status WHERE uid IN (
                                        SELECT uid2 FROM friend WHERE uid1 = me()
                                    ) AND time > ".QUERY_SINCE."
                                )
                            )";
        
            $myLikeLinkQuery = "SELECT owner FROM link WHERE link_id IN (
                                SELECT object_id FROM like 
                                WHERE user_id = me() AND object_id IN (
                                    SELECT link_id FROM link WHERE owner IN (
                                        SELECT uid2 FROM friend WHERE uid1 = me()
                                    ) AND created_time > ".QUERY_SINCE."
                                )
                            )";
            
            $queries['myLikeNoteQuery'] = $myLikeNoteQuery;
            $queries['myLikeStatusQuery'] = $myLikeStatusQuery;
            $queries['myLikeLinkQuery'] = $myLikeLinkQuery;
        }
        
        $data = callMultiFQL($queries);
        
    }catch(FacebookApiException $e){
        throw($e);
    }
    return $data;    
}

//get all activity data for a friend
//param $id : a friend's id
//return $data : result of multiquery
//exception : FacebookApiException
function getActivities($id){
    //messages, post(note, link, status, comment)
    $data = null;
    
    try{
    
        $inMessageQuery = "SELECT message_id, thread_id, author_id, body, created_time FROM message WHERE author_id = '$id' AND thread_id IN (
                            	SELECT thread_id FROM thread WHERE folder_id = 0 AND updated_time > ".QUERY_SINCE."
                        	) AND created_time > ".QUERY_SINCE;
        
        $outMessageQuery = "SELECT message_id, thread_id, author_id, body, created_time FROM message WHERE author_id = me() AND thread_id IN (
                    	SELECT thread_id FROM thread WHERE folder_id = 1 AND updated_time > ".QUERY_SINCE."
                	) AND created_time > ".QUERY_SINCE;
            
        $outThreadQuery = "SELECT thread_id, recipients, subject FROM thread WHERE folder_id = 1 AND thread_id IN (
                            	SELECT thread_id FROM #outMessageQuery
                            )";
        
        $friendCommentQuery = "SELECT object_id, fromid, text, time FROM comment
            			WHERE fromid = '$id' 
            			AND (
            				object_id IN (SELECT note_id FROM note WHERE uid = me() AND created_time > ".QUERY_SINCE.")
            				OR object_id IN (SELECT status_id FROM status WHERE uid = me() AND time > ".QUERY_SINCE.")
            				OR object_id IN (SELECT link_id FROM link WHERE owner = me() AND created_time > ".QUERY_SINCE.")
            			) AND time >".QUERY_SINCE; 
        
        $myCommentQuery = "SELECT object_id, fromid, text, time FROM comment 
                WHERE fromid = me() 
                AND (
    				object_id IN (SELECT note_id FROM note WHERE uid = '$id' AND created_time > ".QUERY_SINCE.")
    				OR object_id IN (SELECT status_id FROM status WHERE uid = '$id' AND time > ".QUERY_SINCE.")
    				OR object_id IN (SELECT link_id FROM link WHERE owner = '$id' AND created_time > ".QUERY_SINCE.")
                ) AND time >".QUERY_SINCE; 

        $friendPostQuery = "SELECT post_id, actor_id, message, created_time FROM stream 
                        WHERE source_id = me() AND actor_id = '$id' AND created_time >".QUERY_SINCE;

        $data = callMultiFQL(array(
            'inMessageQuery'      => $inMessageQuery, 
            'outMessageQuery'     => $outMessageQuery,
            'outThreadQuery'      => $outThreadQuery,
            'friendCommentQuery' => $friendCommentQuery,
            'myCommentQuery'      => $myCommentQuery,
            'friendPostQuery'     => $friendPostQuery
        ));

    }catch(FacebookApiException $e){
        throw($e);
    }
    return $data;       
}


function getFriendsOfFriends(){
    
    $query = "select uid1, uid2 from friend 
    	where uid1 IN (
    		select uid1 from friend where uid2 = me()
    	) and uid2 IN (
    		select uid1 from friend where uid2 = me()
    	) ";
    
    $data = null;
    try{
        $data = callFQL($query);
    }catch(FacebookApiException $e){
        throw($e);
    }
    return $data;
}

function getResultSet($queryName, &$data){
    foreach($data as $query){
        if($query['name'] == $queryName){
            return $query;
        }
    }
}

//parse data and add Activities into input parameter,
function getInMessageActivities($data, &$activities){
    
    //check if it's raw data
    if(isset($data['fql_result_set'])){
        $data = $data['fql_result_set'];
    }
    
    //fill the array
    if(is_array($data) && !empty($data)){
        foreach($data as $message){
            $act = new activity($message['message_id'], "msg", $message['author_id'], str_replace("\n", "", substr($message['body'],0,STRING_LENGTH)), $message['created_time']);
            array_push($activities, $act);
        }
    }
    return $activities;
}

//parse out messages and threads to extract recipients data
//in case of out messages, which is different from in messages, it's impossible to get data from only recipient id
//It can't be helped that get all out messages regardless of recipients, then parse data to extract recipient data later
function getOutMessageActivities($id, $messages, $threads, &$activities){

    //check input $activities is an array
    if(!is_array($activities)){
        return false;
    }
    //check raw data
    if($messages['name'] == "outMessageQuery" && isset($messages['fql_result_set']) && $threads['name'] == "outThreadQuery" && isset($threads['fql_result_set'])){
        $messages = $messages['fql_result_set'];
        $threads = $threads['fql_result_set'];
    } else {
        return false;
    }
    
    //fill the array
    if(is_array($messages) && is_array($threads) && !empty($messages) && !empty($threads)){

        //first check threads sent to the id
        foreach($threads as $thread){
            $recipients = $thread['recipients'];
            $thread_id = $thread['thread_id'];
            foreach($recipients as $recipient){
                if($recipient == $id){
                    //find messages in $thread_id
                    foreach($messages as $message){
                        if($message['thread_id'] == $thread_id){
                            $act = new activity($message['message_id'], "msg", $message['author_id'], str_replace("\n", "", substr($message['body'],0,STRING_LENGTH)), $message['created_time']);
                            array_push($activities, $act);
                        }
                    } 
                }
            }
        }
        
    }
    
    return $activities;
    
    
}

//parse the friend's post data then return activities array
function getFriendPostActivities($data, &$activities){
    //check input $activities is an array
    if(!is_array($activities)){
        return false;
    }
    //check raw data
    if($data['name'] == "friendPostQuery" && isset($data['fql_result_set'])){
        $data = $data['fql_result_set'];
    } else {
        return false;
    }
    
    //fill out the array
    if(is_array($data) && !empty($data)){
        foreach($data as $post){
            $act = new activity($post['post_id'], "post", $post['actor_id'], $post['message'], $post['created_time']);
            array_push($activities, $act);
        }
    }
    return $activities;
}

//parse the friend's comment data then return activities array
function getFriendCommentActivities($data, &$activities){
    //check input $activities is an array
    if(!is_array($activities)){
        return false;
    }
    //check raw data
    if($data['name'] == "friendCommentQuery" && isset($data['fql_result_set'])){
        $data = $data['fql_result_set'];
    } else {
        return false;
    }
    if(is_array($data) && !empty($data)){
        foreach($data as $comment){
            $act = new activity($comment['object_id'], "comment", $comment['fromid'], str_replace("\n", "", substr($comment['text'],0,STRING_LENGTH)), $comment['time']);
            array_push($activities, $act);        
        }
    }
    return $activities;
}

//parse my comments on the friend's posts, fill out activities array then return it
function getMyCommentActivities($data, &$activities){
    //check input $activities is an array
    if(!is_array($activities)){
        return false;
    }
    //check raw data
    if($data['name'] == "myCommentQuery" && isset($data['fql_result_set'])){
        $data = $data['fql_result_set'];
    } else {
        return false;
    }
    
    //fill out the array
    foreach($data as $comment){
        $act = new activity($comment['object_id'], "comment", $comment['fromid'], str_replace("\n", "", substr($comment['text'],0,STRING_LENGTH)), $comment['time']);
        array_push($activities, $act);
    }
    return $activities;
    
}

//Get thread, message data and parsing the data and fill empty friends array with relevant information
function processMessages(&$friends, &$threads, &$messages){

    global $session;
    
    if(isset($threads['fql_result_set'])){
        $threads = $threads['fql_result_set'];
    }
    if(isset($messages['fql_result_set'])){
        $messages = $messages['fql_result_set'];
    }
    
    //parse data and create new thread array
    //$threadData = array(
    //             'thread_id' => array( 'sender' => sender_id , 'recipients' => recipients array)
    //)
    $threadData = array();
    foreach($threads as $thread){
        if(!array_key_exists($thread['thread_id'], $threadData)){

            $threadData[$thread['thread_id']]['sender'] = $thread['recipients'][0];
            
            if($thread['recipients'][0] == $session['uid']){
                $threadData[$thread['thread_id']]['recipients'] = array_slice($thread['recipients'], 1);                    
            } else {
                $threadData[$thread['thread_id']]['recipients'] = array($session['uid']);
            }

        }
    }
    
    $repliers = array();
    foreach($messages as $message){
        if(array_key_exists($message['thread_id'], $repliers)){
            //add replier
            array_push($repliers[$message['thread_id']], $message['author_id']);
        }else{
            //create an array
            $repliers[$message['thread_id']] = array($message['author_id']);
        }
    }
    
    foreach($threadData as $thread_id => $thread){
        //if sender is oneself
        if($thread['sender'] == $session['uid']){
            foreach($thread['recipients'] as $recipient){
                
                if(array_key_exists($thread_id, $repliers) && array_search($recipient, $repliers[$thread_id])){
                    //there is the friend in the array
                    if(isset($friends[$recipient]) && $friends[$recipient] instanceof Friend){
                        $friends[$recipient]->increaseTwoWayMessages();
                    }else{
                        //if the friend is new, first create and increase and push
                        $f = new Friend($recipient, null);
                        $f->increaseTwoWayMessages();
                        array_push($friends, $f);
                    }
                } else {
                    if(isset($friends[$recipient]) && $friends[$recipient] instanceof Friend){
                        $friends[$recipient]->increaseOneWayMessages();
                    }else{
                        //if the friend is new, first create and increase and push
                        $f = new Friend($recipient, null);
                        $f->increaseOneWayMessages();
                        array_push($friends, $f);
                    }
                }
            }

        }else{
        //if sender is a friend, try to find myself among the repliers otherwise the sender count one-way

            if(array_key_exists($thread_id, $repliers) && array_search($session['uid'], $repliers[$thread_id])){
                if(isset($friends[$thread['sender']]) && $friends[$thread['sender']] instanceof Friend){
                    $friends[$thread['sender']]->increaseTwoWayMessages();
                }else{
                    //if the friend is new, first create and increase and push
                    $f = new Friend($thread['sender'], null);
                    $f->increaseTwoWayMessages();
                    array_push($friends, $f);
                }
            } else {
                if(isset($friends[$thread['sender']]) && $friends[$thread['sender']] instanceof Friend){
                    $friends[$thread['sender']]->increaseOneWayMessages();
                }else{
                    $f = new Friend($thread['sender'], null);
                    $f->increaseOneWayMessages();
                    array_push($friends, $f);
                }
            }
        }
    }    
    
}

//Processing friends' comments on my posts
function processFriendsComments(&$friends, &$comments){
    
    if(isset($comments['fql_result_set'])){
        $comments = $comments['fql_result_set'];
    }
    
    if(!empty($comments) && is_array($comments)){
        foreach ($comments as $comment){
            $fId = $comment['fromid'];
            if(isset($friends[$fId]) && ($friends[$fId] instanceof Friend)){
                $friends[$fId]->increaseComments();
            } else {
                $f = new Friend($fId, null);
                $f->increaseComments();
                array_push($friends, $f);
            }
        }
    }
}

//Processing my comments on friends' posts
function processMyComments(&$friends, $object_array){

    if(!empty($object_array) && is_array($object_array)){
        foreach ($object_array as $objects){
            if(!empty($objects['fql_result_set']) && is_array($objects['fql_result_set'])){
                foreach($objects['fql_result_set'] as $object){
                    $fId = array_pop($object);
                    if(isset($friends[$fId]) && ($friends[$fId] instanceof Friend)){
                        $friends[$fId]->increaseComments();
                    } else {
                        $f = new Friend($fId, null);
                        $f->increaseComments();
                        array_push($friends, $f);
                    }
                }
            }
        }
    }
}

function processFriendsLikes(&$friends, $likes){
    
    if(isset($likes['fql_result_set'])){
        $likes = $likes['fql_result_set'];
    }
    
    if(!empty($likes) && is_array($likes)){
        foreach ($likes as $like){
            $fId = $like['user_id'];
            if(isset($friends[$fId]) && ($friends[$fId] instanceof Friend)){
                $friends[$fId]->increaseLikes();
            } else {
                $f = new Friend($fId, null);
                $f->increaseLikes();
                array_push($friends, $f);
            }
        }
    }    
}

function processMyLikes(&$friends, $object_array){
    if(!empty($object_array) && is_array($object_array)){
        foreach ($object_array as $objects){
            if(!empty($objects['fql_result_set']) && is_array($objects['fql_result_set'])){
                foreach($objects['fql_result_set'] as $object){
                    $fId = array_pop($object);
                    if(isset($friends[$fId]) && ($friends[$fId] instanceof Friend)){
                        $friends[$fId]->increaseLikes();
                    } else {
                        $f = new Friend($fId, null);
                        $f->increaseLikes();
                        array_push($friends, $f);
                    }
                }
            }
        }
    }
}

function processFriendsPostsOnMyWall(&$friends, $posts){
    if($posts['name'] == "friendsPostQuery" && isset($posts['fql_result_set'])){
        $posts = $posts['fql_result_set'];
    }
    if(is_array($posts) && !empty($posts)){
        foreach($posts as $post){
            $fId = $post['actor_id'];
            if(isset($friends[$fId]) && ($friends[$fId] instanceof Friend)){
                $friends[$fId]->increasePosts();
            } else {
                $f = new Friend($fId, null);
                $f->increaseLikes();
                array_push($friends, $f);
            }
        }
    }
}


//Check if the current session is valid by making a simple api call and get $me back
//if it's valid return true otherwise return false;
function checkSessionValidity(){
    global $facebook;
    if(getOneself()){
        return true;
    }
    return false;
}

//return user object returned by '/me' api call
function getOneself(){
    global $facebook;
    $me = null;
    try{
        $me = $facebook->api('/me?fields=id,link');
    } catch (FacebookApiException $e){
        throw($e);
    }
    return $me;
}

//get wall posts
//param : $uid (Facebook user id)
function getWallPosts($uid){
    global $facebook;
    $posts = null;

    try{
        $response= $facebook->api('/'.$uid.'/feed?fields=from,comments&since='.QUERY_SINCE);
        //$response= $facebook->api('/'.$uid.'/feed?limit=3');
        if(!empty($response['data'])){
            $posts = $response['data'];
        }
    }catch(FacebookApiException $e){
        throw($e);
    }

    return $posts;   
}

function processingWallPostsOnMyWall(&$friends){
    
    global $me;
    $posts = getWallPosts($me['id']);
  
    if(!empty($posts)){
        foreach($posts as $post){
            //if it's friends' posts
            if($me['id'] != $post['from']['id']){
                $fId = $post['from']['id'];
                $flag = 1;
                
                //check comments if there is a comment from me
                $comments = getComments($post['id']);
                if(existFromId($comments, $me['id'])){
                    $flag = 2;
                }
                
                //increase relevant communication number
                if($flag == 2){
                    $friends[$fId]->increasePosts();
                } else {
                    $friends[$fId]->increasePosts();
                }
                
            } else {
                //if it's my posts
                //check comments if there is a comment from friends
                $comments = getComments($post['id']);
                if(!empty($comments)){
                    foreach($comments as $comment){
                        if(!empty($comment['from']['id']) && $comment['from']['id'] != $me['id']){
                            $fId = $comment['from']['id'];
                            $friend = $friends[$fId];
                            if(!empty($friend) && $friend instanceof Friend){
                                $friends[$fId]->increasePosts();
                            }
                        }
                    }
                }
            }
        }
    }        

}

function existFromId($comments, $id){
    if(!empty($comments)){
        foreach($comments as $comment){
            if(!empty($comment['from']['id']) && $id == $comment['from']['id']){
                return true;
            }
        }
    }
    return false;
}

/* Deprecated


//Issue : Took too much time
function getPostsWithAllCommentsFQL(){
    
    global $facebook;

    $response = null;
    try{
        $response = callFQL("SELECT uid,status_id,message FROM status WHERE uid = me()");
    }catch( $e){
        print($e);
    }

    return $response;
}

function getFriendsRanking(){
    
	$friends = null;
	$me = getOneself();
	
	if($me){
		
		//Get Friends
		$friends = getFriends();
	
		//Process Inbox Messages
		processInboxMessages($friends);
		
		//Process Outbox Messages
		processOutboxMessages($friends);
		
		//Process Friends' Posts on my wall 
		//processingWallPostsOnMyWall($friends);
		processFriendsComments($friends);
		processMyComments($friends);
		
		//Process Like
		processFriendsLikes($friends);
        processMyLikes($friends);
		
		//sort
		uasort($friends, 'cmp');
	}
	
	return $friends;		
}

/*
 * maybe I can make use of graph api /{post_id}/comments
 * found some defect in my code. There can be more response than the response below because of paging!
 * but the limit seems to be 25 comments, and it's quite enough number (imagine a message thread with over 25 comments)
 * When I use graph api to get comments, it took too long. So, I changed my mind to use FQL way
 * /
 */
/* deprecated
function getInboxMessages(){

    $data = null;
    try{
        $response = callGraphAPI('/me/inbox?fields=from,comments&since='.QUERY_SINCE);
   	    $data = $response['data'];
    }catch( $e){
        error_log($e);
    }

    return $data;
}

function getOutboxMessages(){

    $data = null;
    try {
        $response = callGraphAPI('/me/outbox?fields=from,to,comments&since='.QUERY_SINCE);
        //$response = $facebook->api('me/outbox?limit=3');
        $data = $response['data'];
    }catch( $e){
        error_log($e);
    }
    return $data;
}

//count one-way, two-way communications in Inbox
//only concerns messages from others (inbox! which means excluding messages from oneself, it will be dealt with in outbox functions)
function processInboxMessages(&$friends){
	
	global $me;
	
	$uid = $me['id'];

	//Get inbox messages
	$messages = getInboxMessages();

	if($messages != null){
	
    	//Go through the array
    	foreach ($messages as $msg) {
    		
    		$fId = $msg['from']['id'];
    		
    		//exclude the user
    		if($fId != $uid){
    
    			$flag = 1;
    			
    			//Look at comments and if there is the user's comment, that is a reciprocated communication otherwise, unidirectional communication
    			if(!empty($msg['comments'])){
    				
    				$comments = $msg['comments'];
    				
    				if($comments){
    					foreach ($comments['data'] as $comment) {
    						if($comment['from']['id'] == $uid){
    							//Reciprocated communication
    							$flag = 2;
    							break;
    						}
    					}
    				}
    			}
    			//Ignore non-friend senders
    			if(!empty($friends[$fId])){
    				if($flag == 2){
    					$friends[$fId]->increaseTwoway();
    				} else {
    					$friends[$fId]->increaseOneway();
    				}
    			}
    		}
    	}
    }
    return $friends;

}

//Processing Outward Messages 
function processOutboxMessages(&$friends){
	
	global $me;
	
	$uid = $me['id'];

	//Get inbox messages
	$messages = getOutboxMessages();

	if($messages != null){
	
    	//Go through the array
    	foreach ($messages as $msg) {
    		
    		$senderId = $msg['from']['id'];
    		
    		//messages only sent by oneself
    		if($senderId == $uid){
    
    		    //compare receivers(to) with commenters(comments from)
    		    $receivers = $msg['to']['data'];

    		    
    		    if(!empty($receivers) && is_array($receivers)){
    		        foreach($receivers as $receiver){
    		            $fId = $receiver['id'];
    			        $flag = 1;

    			        if(!empty($msg['comments']) && !empty($msg['comments']['data']) && is_array($msg['comments']['data'])){
                            $comments = $msg['comments']['data'];
                            foreach($comments as $comment){
                                //if there is a commentor who received the message
                                if($fId == $comment['from']['id']){
                                    $flag = 2;
                                }
                            }                           
    			        }
    			        
    			        if(!empty($friends[$fId])){
                            if($flag == 2){
                                $friends[$fId]->increaseTwoway();
                            } else {
                                $friends[$fId]->increaseOneway();
                            }
    			        }
    			        
    		        }
    		    }
    		    
    		}
    	}
    }
    return $friends;
}

function getFriendsRankingJSON(){

    $json = null;

    //Get Friends
    $friends = getFriendsRanking();

    //JSON encoding
    $json = "[";

    $isFirst = true;
    foreach($friends as $f){
        if(!$isFirst)
        $json .= ",";
        $json .= "{";
        $json .= "'fId' : '".$f->getfId()."',";
        $json .= "'name' : '".$f->getName()."',";
        $json .= "'score' : '".$f->getScore()."'";
        $json .= "}";
        $isFirst = false;
    }

    $json .= "]";

    //return output
    return $json;
}

//get message data by multi FQL query
function getMessagesByFQL(){
    
    $threadQuery = "select thread_id, recipients from thread where folder_id = 0 or folder_id = 1 and updated_time > ".QUERY_SINCE;
    
    $messageQuery = "select thread_id, author_id from message where thread_id in (
    	select thread_id from #query1
	) and created_time > ".QUERY_SINCE;

    $response = null; 
    try{
        $response = callMultiFQL(array(
            'threadQuery' => $threadQuery,
            'messageQuery' => $messageQuery
        ));
    }catch( $e){
        error_log($e);
    }
    return $response;
    
}

//Friends' Comments on my posts
function getFriendCommentsOnMyPostByFQL(){
    global $facebook;
    $data = null;
    try{
        //Friends' comments on my post
        $data = callFQL("SELECT fromid FROM comment
        			WHERE fromid != me() 
        			AND (
        				object_id IN (SELECT note_id FROM note WHERE uid = me())
        				OR object_id IN (SELECT status_id FROM status WHERE uid = me())
        				OR object_id IN (SELECT link_id FROM link WHERE owner = me())
        			) AND time >".QUERY_SINCE);
    }catch( $e){
        error_log($e);
    }
    return $data;
}

//My Comments on friends' posts
function getMyCommentsOnFriendsPostFQL(){
    global $facebook;
    $data = null;
    try{
        //Friends' comments on my post
        $noteQuery = "SELECT uid FROM note WHERE note_id IN (
                                SELECT object_id FROM comment 
                                WHERE fromid = me() AND object_id IN (
                                    SELECT note_id FROM note WHERE uid IN (
                                        SELECT uid2 FROM friend WHERE uid1 = me()
                                    )
                                )
                            )";
        
        $statusQuery = "SELECT uid FROM status WHERE status_id IN (
                                SELECT object_id FROM comment 
                                WHERE fromid = me() AND object_id IN (
                                    SELECT status_id FROM status WHERE uid IN (
                                        SELECT uid2 FROM friend WHERE uid1 = me()
                                    )
                                )
                            )";
        
        $linkQuery = "SELECT owner FROM link WHERE link_id IN (
                                SELECT object_id FROM comment 
                                WHERE fromid = me() AND object_id IN (
                                    SELECT link_id FROM link WHERE owner IN (
                                        SELECT uid2 FROM friend WHERE uid1 = me()
                                    )
                                )
                            )";
$now = time();        
        $data = $facebook->api(
            array(
            	'method' => 'fql.multiquery',
                'queries' => array(
                	"note" => $noteQuery,
                	"status" => $statusQuery,
                	"link" => $linkQuery
                )
            )
        );
error_log("Elapsed time for getMyComments : ".(time() - $now));        
    }catch(FacebookApi $e){
        error_log($e);
    }
    return $data;    
}

//Friends' Likes on My posts
function getFriendsLikesOnMyPostsByFQL(){
    global $facebook;
    $data = null;
    try{
        //Friends who liked my post
        $data = $facebook->api(
            array(
            	'method' => 'fql.query',
                'query' => "SELECT user_id FROM like 
        			WHERE user_id != me() 
        			AND (
        				object_id IN (SELECT note_id FROM note WHERE uid = me())
        				OR object_id IN (SELECT status_id FROM status WHERE uid = me())
        				OR object_id IN (SELECT link_id FROM link WHERE owner = me())
        			)"
            )
        );
    }catch(FacebookApi $e){
        error_log($e);
    }
    return $data;
}

//My Likes on Friends' posts
function getMyLikeOnFriendsPostFQL(){
    global $facebook;
    $data = null;
    try{

        $noteQuery = "SELECT uid FROM note WHERE note_id IN (
                                SELECT object_id FROM like 
                                WHERE user_id = me() AND object_id IN (
                                    SELECT note_id FROM note WHERE uid IN (
                                        SELECT uid2 FROM friend WHERE uid1 = me()
                                    )
                                )
                            )";
        
        $statusQuery = "SELECT uid FROM status WHERE status_id IN (
                                SELECT object_id FROM like 
                                WHERE user_id = me() AND object_id IN (
                                    SELECT status_id FROM status WHERE uid IN (
                                        SELECT uid2 FROM friend WHERE uid1 = me()
                                    )
                                )
                            )";
        
        $linkQuery = "SELECT owner FROM link WHERE link_id IN (
                                SELECT object_id FROM like 
                                WHERE user_id = me() AND object_id IN (
                                    SELECT link_id FROM link WHERE owner IN (
                                        SELECT uid2 FROM friend WHERE uid1 = me()
                                    )
                                )
                            )";
$now = time();
        $data = $facebook->api(
            array(
            	'method' => 'fql.multiquery',
                'queries' => array(
                	"note" => $noteQuery,
                	"status" => $statusQuery,
                	"link" => $linkQuery
                )
            )
        );
error_log("Elapsed time for getMyLikes : ".(time() - $now));
    }catch(FacebookApi $e){
        error_log($e);
    }
    return $data;        
}

//get comment array on a certain object(status, link, note, photo, etc)
//param : $objectId (Facebook object id)
//performance issue : too slow
function getComments($objectId){
    global $facebook;
    $comments = null;
    try{
        if(!empty($objectId)){
            $response = $facebook->api('/'.$objectId.'/comments?fields=from');
            if(!empty($response['data'])){
                $comments = $response['data'];
            }
        }
    }catch(FacebookApi $e){
        error_log($e);
    }
    return $comments;
}

*/